package com.study.signin_demo2.class03;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;

/**
 * @author whx
 * @date 2022/2/21
 */
public class C10_ForVsStream {

    private static final Integer MAX_SIZE = 5000000;
    /**
     * 1～99999999的500W条数据，找到其中的最大值
     * @param args
     */
    public static void main(String[] args) {
        List<Long> forTest = new ArrayList<>();
        List<Long> streamTest = new ArrayList<>();
        // 循环执行100遍，求平均值
        IntStream.range(0, 100).forEach(n -> {
            int[] a = new Random().ints(MAX_SIZE, 1, 99999999).toArray();
            int e = a.length;
            int m = Integer.MIN_VALUE;
            long thisTime = System.nanoTime();
            for (int i = 0; i < e; i++) {
                if (a[i] > m) {
                    m = a[i];
                }
            }
            System.out.println("MAX is " + m);
            Long testRes = System.nanoTime() - thisTime;
            forTest.add(testRes);
            System.out.println("For use time :" + testRes);
            System.out.println(IntStream.of(a).toArray().length);
            thisTime = System.nanoTime();
            m = IntStream.of(a).reduce(0, (x, y) -> x > y ? x : y);
            System.out.println("MAX is " + m);
            testRes = System.nanoTime() - thisTime;
            streamTest.add(testRes);
            System.out.println("StreamSimple use time :" + testRes);
        });

        Long forTotal = forTest.stream().reduce(0L, Long::sum);
        Long streamTotal = streamTest.stream().reduce(0L, Long::sum);
        System.out.println("For total cost: " + forTotal
                + ", min cost: " + forTest.stream().reduce(Long::min).orElse(0L) + ", average cost : " + forTotal / 100);
        System.out.println("Stream total cost: " + streamTotal
                + ", min cost: " + streamTest.stream().reduce(Long::min).orElse(0L) + ", average cost : " + streamTotal / 100);
    }
}
